﻿using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System.Collections.Generic;

namespace Framework.UGUI
{
    //ui点击穿透，挂在要穿透的组件上，开启要穿透的类型（点击，按下，弹起）
    public class UITouchPenetrate : MonoBehaviour, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler
    {
        //true:穿透一层
        //false：穿透多层
        public bool penetrateOneLayer = true;
        public bool enabledClick = false;
        public bool enabledDown = false;
        public bool enabledUp = false;

        public void OnPointerClick(PointerEventData eventData)
        {
            if (enabledClick)
                PassEvent(eventData, ExecuteEvents.pointerClickHandler);
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            if (enabledDown)
                PassEvent(eventData, ExecuteEvents.pointerDownHandler);
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            if (enabledUp)
                PassEvent(eventData, ExecuteEvents.pointerUpHandler);
        }

        private List<RaycastResult> results = new List<RaycastResult>();

        //把事件透下去
        public void PassEvent<T>(PointerEventData data, ExecuteEvents.EventFunction<T> function)
            where T : IEventSystemHandler
        {
            var currentEventSystem = EventSystem.current;
            if (currentEventSystem == null)
                return;

            currentEventSystem.RaycastAll(data, results);
            GameObject current = data.pointerCurrentRaycast.gameObject;
            for (int i = 0; i < results.Count; i++)
            {
                var resultGo = results[i].gameObject;
                if (current != resultGo && !resultGo.transform.IsChildOf(transform))
                {
                    //SLLogger.Log("PassEvent:" + resultGo.name);
                    ExecuteEvents.Execute(resultGo, data, function);
                    if (penetrateOneLayer)
                    {
                        //只触发一层事件
                        break;
                    }
                }
            }
        }
    }
}